package worker

import (
	"fmt"
	"go_job/common"
	"math/rand"
	"os/exec"
	"time"
)

type Executor struct {
}

var (
	G_executor *Executor
)

func (executor *Executor) ExecuteJob(info *common.JobExecuteInfo) {
	go func() {
		var (
			comm      *exec.Cmd
			err       error
			output    []byte
			res       *common.JobExecuteResult
			startTime time.Time
			jobLock   *JobLock
		)
		//执行shell
		res = &common.JobExecuteResult{
			ExecuteInfo: info,
			OutPut:      make([]byte, 0),
		}

		jobLock = G_jobMgr.CreateJobLock(info.Job.Name)

		time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
		err = jobLock.TryLock()
		defer jobLock.Unlock()

		if err != nil {
			res.Err = err
			res.StartTime = time.Now()
			res.EndTime = time.Now()
		} else {
			startTime = time.Now()

			comm = exec.CommandContext(info.CancelCtx, "/bin/bash", "-c", info.Job.Command)

			output, err = comm.CombinedOutput()

			res.Err = err
			res.StartTime = startTime
			res.OutPut = output
			res.EndTime = time.Now()
			jobLock.Unlock()
		}
		G_Scheduler.PushJobExeResult(res)
	}()
}

func InitJobExecutor() (err error) {
	G_executor = &Executor{}
	fmt.Println("任务执行器启动")
	return
}
